const OrderDao = require('./OrderDao');

class AIDao {
    constructor(pool) {
        this.pool = pool;
        this.orderDao = new OrderDao(pool);
    }

    /**
     * 保存AI交互记录
     * @param {number} user_id - 用户ID
     * @param {string} interaction_type - 交互类型（农业咨询/数据查询）
     * @param {string} question - 用户问题
     * @param {string} response - AI回答
     * @param {string} created_at - 创建时间（可选，默认为当前时间）
     * @returns {Promise} - 数据库操作结果
     */
    async saveInteraction(user_id, interaction_type, question, response, created_at = null) {
        try {
            // 获取东8区时间
            var timestamp = new Date(new Date().getTime() + 8 * 60 * 60 * 1000).toISOString().slice(0, 19).replace('T',' ');
            
            const sql = `
                INSERT INTO ai_interactions(
                    interaction_id,
                    user_id,
                    interaction_type,
                    question,
                    response,
                    created_at
                ) VALUES (DEFAULT, ?, ?, ?, ?, ?)
            `;
            
            const [result] = await this.pool.execute(sql, [
                user_id,
                interaction_type,
                question,
                response,
                timestamp
            ]);
            
            return {
                success: true,
                data: {
                    interaction_id: result.insertId,
                    user_id,
                    interaction_type,
                    question,
                    response,
                    created_at: timestamp
                }
            };
        } catch (error) {
            console.error('保存AI交互记录失败:', error);
            return {
                success: false,
                error: error.message
            };
        }
    }

    /**
     * 获取用户的AI交互历史记录
     * @param {number} user_id - 用户ID
     * @param {string} interaction_type - 交互类型（农业咨询/数据查询）
     * @param {number} limit - 限制返回记录数量
     * @returns {Promise} - 数据库操作结果
     */
    async getUserInteractions(user_id, interaction_type, limit = 10) {
        try {
            const sql = `
                SELECT * FROM ai_interactions
                WHERE user_id = ? AND interaction_type = ?
                ORDER BY created_at DESC
                LIMIT ${limit}
            `;
            const [rows] = await this.pool.execute(sql, [user_id, interaction_type]);
            // 将结果数组反转，使其按时间正序排列
            const orderedRows = rows.reverse();
            return {
                success: true,
                data: orderedRows
            };
        } catch (error) {
            console.error('获取用户AI交互记录失败:', error);
            return {
                success: false,
                error: error.message
            };
        }
    }

    /**
     * 清空用户的AI交互历史记录
     * @param {number} user_id - 用户ID
     * @param {string} interaction_type - 交互类型（农业咨询/数据查询）
     * @returns {Promise} - 数据库操作结果
     */
    async clearUserInteractions(user_id, interaction_type) {
        try {
            const sql = `
                DELETE FROM ai_interactions 
                WHERE user_id = ? AND interaction_type = ?
            `;
            const [result] = await this.pool.execute(sql, [user_id, interaction_type]);
            
            return {
                success: true,
                data: {
                    affectedRows: result.affectedRows
                }
            };
        } catch (error) {
            console.error('清空用户AI交互记录失败:', error);
            return {
                success: false,
                error: error.message
            };
        }
    }

    // 获取政府收购数据
    async getGovBuy() {
        try {
            const sql = `
                SELECT * FROM articles
                natural join users
                where role_name = 'gov'
            `;
            const [rows] = await this.pool.execute(sql);
            
            if (rows.length > 0) {
                let result = "当前政府正在收购的农产品信息如下：\n";
                rows.forEach(article => {
                    // console.log(`用户ID：${article.user_id}\n`)
                    result += `\n【${article.title}】\n`;
                    result += `政府ID：${article.user_id}\n`;
                    result += `政府名称：${article.nick_name}\n`;
                    result += `产品名称：${article.product_name}\n`;
                    result += `产品类别：${article.product_category}\n`;
                    result += `收购价格：${article.price_offer}元/斤\n`;
                    result += `总收购量：${article.total_quantity}斤\n`;
                    result += `剩余收购量：${article.remaining_quantity}斤\n`;
                    result += `收购地区：${article.region}\n`;
                    result += `发布时间：${new Date(article.published_at).toLocaleString()}\n`;
                    result += `截止时间：${new Date(article.deadline).toLocaleString()}\n`;
                    result += `电话：${article.user_phone}\n`;
                    result += `邮箱：${article.user_email}\n`;
                    result += `详细说明：${article.content}\n`;
                });
                return result;
            }
            return "暂无政府收购信息";
        } catch (error) {
            console.error('获取政府收购数据失败:', error);
            return "获取政府收购数据失败";
        }
    }

    // 获取政府出售数据
    async getGovSell() {
        try {
            const sql = `
                select * from agri_products
                natural join users
                where role_name = 'gov' AND status = 'active'
            `;
            const [rows] = await this.pool.execute(sql);
            
            if (rows.length > 0) {
                let result = "当前政府正在出售的农产品信息如下：\n";
                rows.forEach(product => {
                    result += `\n【${product.product_name}】\n`;
                    result += `政府ID：${product.user_id}\n`;
                    result += `政府名称：${product.nick_name}\n`;
                    result += `类别：${product.category}\n`;
                    result += `价格：${product.price}元/斤\n`;
                    result += `目前库存：${product.total_stock}\n`;
                    result += `上架数量：${product.listed_quantity}\n`;
                    result += `销售地区：${product.region}\n`;
                    result += `发布时间：${new Date(product.created_at).toLocaleString()}\n`;
                    result += `手机：${product.user_phone}\n`;
                    result += `邮箱：${product.user_email}\n`;
                    if (product.description) {
                        result += `描述：${product.description}\n`;
                    }
                    if (product.introduction) {
                        result += `详细介绍：${product.introduction}\n`;
                    }
                });
                return result;
            }
            return "暂无政府出售信息";
        } catch (error) {
            console.error('获取政府出售数据失败:', error);
            return "获取政府出售数据失败";
        }
    }

    // 获取经销商收购数据
    async dealerBuy() {
        try {
            const sql = `
                SELECT * FROM articles
                natural join users
                where role_name = 'dealer'
            `;
            const [rows] = await this.pool.execute(sql);
            
            if (rows.length > 0) {
                let result = "当前经销商正在收购的农产品信息如下：\n";
                rows.forEach(article => {
                    result += `\n【${article.title}】\n`;
                    result += `经销商ID：${article.user_id}\n`;
                    result += `经销商名称：${article.nick_name}\n`;
                    result += `产品名称：${article.product_name}\n`;
                    result += `产品类别：${article.product_category}\n`;
                    result += `收购价格：${article.price_offer}元/斤\n`;
                    result += `总收购量：${article.total_quantity}斤\n`;
                    result += `剩余收购量：${article.remaining_quantity}斤\n`;
                    result += `收购地区：${article.region}\n`;
                    result += `发布时间：${new Date(article.published_at).toLocaleString()}\n`;
                    result += `截止时间：${new Date(article.deadline).toLocaleString()}\n`;
                    result += `手机：${article.user_phone}\n`;
                    result += `邮箱：${article.user_email}\n`;
                    result += `详细说明：${article.content}\n`;
                });
                return result;
            }
            return "暂无经销商收购信息";
        } catch (error) {
            console.error('获取经销商收购数据失败:', error);
            return "获取经销商收购数据失败";
        }
    }

    // 获取农户出售数据
    async farmerSell() {
        try {
            const sql = `
                select * from agri_products
                natural join users
                where role_name = 'farmer' AND status = 'active'
            `;
            const [rows] = await this.pool.execute(sql);
            
            if (rows.length > 0) {
                let result = "当前农户正在出售的农产品信息如下：\n";
                rows.forEach(product => {
                    result += `\n【${product.product_name}】\n`;
                    result += `农户ID：${product.user_id}\n`;
                    result += `农户名称：${product.nick_name}\n`;
                    result += `类别：${product.category}\n`;
                    result += `价格：${product.price}元/斤\n`;
                    result += `目前库存：${product.listed_quantity}\n`;
                    result += `上架数量：${product.total_stock}\n`;
                    result += `销售地区：${product.region}\n`;
                    result += `发布时间：${new Date(product.created_at).toLocaleString()}\n`;
                    result += `手机：${product.user_phone}\n`;
                    result += `邮箱：${product.user_email}\n`;
                    if (product.description) {
                        result += `描述：${product.description}\n`;
                    }
                    if (product.introduction) {
                        result += `详细介绍：${product.introduction}\n`;
                    }
                });
                return result;
            }
            return "暂无农户出售信息";
        } catch (error) {
            console.error('获取农户出售数据失败:', error);
            return "获取农户出售数据失败";
        }
    }

    async getMyOrders(user_id){
        try {
            // 调用OrderDao的getOrdersBySeller方法获取数据
            const orders = await this.orderDao.getOrdersBySeller(user_id);
            // console.log(orders)
            if (orders && orders.length > 0) {
                let result = "您的交易订单信息如下：\n";
                orders.forEach(order => {
                    result += `\n【订单ID：${order.order_id}】\n`;
                    result += `产品名称：${order.product_name}\n`;
                    result += `产品类别：${order.category}\n`;
                    result += `交易方：${order.counterparty}\n`;
                    result += `数量：${order.quantity}\n`;
                    result += `价格：${order.price}元/斤\n`;
                    // result += `订单状态：${order.status}\n`;
                    result += `订单类型(我的行为)：${order.type}\n`;
                    result += `创建时间：${new Date(order.order_created_at).toLocaleString()}\n`;
                    if (order.remarks) {
                        result += `备注：${order.remarks}\n`;
                    }
                });
                return result;
            }
            return "暂无订单信息";
        } catch (error) {
            console.error('获取订单数据失败:', error);
            return "获取订单数据失败";
        }
    }
}

module.exports = AIDao;